package com.cnhis.cloudhealth.clinical.clidoctor.removeAdvice.bo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import com.cnhis.cloudhealth.commons.util.DateUtil;
import com.cnhis.cloudhealth.commons.utils.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cnhis.cloudhealth.clinical.clidoctor.clibackadvice.bo.CliBackAdviceBo;
import com.cnhis.cloudhealth.clinical.clidoctor.cliparamter.dao.CliParamterDao;
import com.cnhis.cloudhealth.clinical.clidoctor.removeAdvice.dao.RemoveAdviceDao;
import com.cnhis.cloudhealth.commons.Mappers.ModelVo;
import com.cnhis.cloudhealth.commons.commonSql.bo.YaopinKucunBo;
import com.cnhis.cloudhealth.commons.newid.GetNewId;
import com.cnhis.cloudhealth.commons.utils.GlobalVariable;
import com.cnhis.cloudhealth.commons.utils.JsonUtil;
import com.cnhis.cloudhealth.commons.utils.StaticKeys;
@Service
public class RemoveAdviceBo {

	@Resource
	private RemoveAdviceDao dao;
	@Autowired
    private GetNewId getNewId;
	@Resource
	private CliParamterDao paraDao;
	@Resource
    private CliBackAdviceBo cliBackAdviceBo;
	@Resource
	private YaopinKucunBo yaopinKucunBo;
	
	private Logger log = Logger.getLogger(RemoveAdviceBo.class);

    public ModelVo removeAdvice(Map<String, Object> map)
    {
        ModelVo mo = new ModelVo();
        try
        {
            //强制类型转换
            String vaf01s = (String)map.get("vaf01s");
            String[] tempArr = vaf01s.split(",");
            List<String> vaf01List = new ArrayList<String>();
            for(String temp : tempArr)
            {
                vaf01List.add(temp);
            }
            map.put("vaf01List", vaf01List);
            //删除医嘱、诊断、诊疗申请单信息，插入操作记录
            long t1 = System.currentTimeMillis();
            dao.update("removeAdvice.shanchuyizhu", map);
            long t2 = System.currentTimeMillis();
            log.info("============删除医嘱耗时====="+(t2-t1)+"毫秒===================");
            mo.setResult(StaticKeys.OH_SUCCESS);
            return mo;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
    }
    public ModelVo removeAdvice1(Map<String, Object> map)
    {
        ModelVo mo = new ModelVo();
        try
        {
            //强制类型转换
            String vaf01s = (String)map.get("vaf01s");
            String[] tempArr = vaf01s.split(",");
            List<String> vaf01List = new ArrayList<String>();
            for(String temp : tempArr)
            {
                vaf01List.add(temp);
            }
            map.put("vaf01List", vaf01List);
            
            
            //查询vaf1表中需要删除的vaf01和vbg1表中需要删除的vbg01
            List<Map<String,Object>> vaf1List  = dao.queryVaf1List(map);
            //查询vaf1表中不需要删除的记录
            List<Map<String,Object>> vaf1LeftList  = dao.queryVaf1LeftList(map);
            
            //要新增的医嘱操作记录
            List<Map<String,Object>> vbg1List = new ArrayList<Map<String,Object>>();
            
            List<String> cbm01List1 = new ArrayList<String>();
            List<String> cbm01List2 = new ArrayList<String>();
            
            List<String> vaf51List1 = new ArrayList<String>();
            List<String> vaf51List2 = new ArrayList<String>();
            for(Map<String,Object> temp1 : vaf1List)
            {
                cbm01List1.add(temp1.get("cbm01").toString());
                vaf51List1.add(temp1.get("vaf51").toString());
                
                Map<String,Object> temp2 = new HashMap<String,Object>();
                temp2.put("vbg01", getNewId.nextId());
                temp2.put("vaf01", temp1.get("vaf01"));
                temp2.put("vbg03", 1);
                temp2.put("bce03", map.get("bce03"));
                temp2.put("vbg06", "医嘱删除操作");
                vbg1List.add(temp2);
            }
            for(Map<String,Object> temp2 : vaf1LeftList)
            {
                Object object = temp2.get("cbm01");
                if (object!=null)
                {
                    cbm01List2.add(object.toString());
                }
                vaf51List2.add(temp2.get("vaf51").toString());
            }
            //过滤出cbm1表需要删除记录
            Iterator<String> cbm01List1Ite = cbm01List1.iterator(); 
            while(cbm01List1Ite.hasNext())
            {
                if(cbm01List2.contains(cbm01List1Ite.next()))
                {
                    cbm01List1Ite.remove();
                }
            }
            //过滤vbq1表需要删除的记录
            Iterator<String> vaf51List1Ite = vaf51List1.iterator(); 
            while(vaf51List1Ite.hasNext())
            {
                if(vaf51List2.contains(vaf51List1Ite.next()))
                {
                    vaf51List1Ite.remove();
                }
            }
            
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("cbm01List1", cbm01List1);
            param.put("vbq01List", vaf51List1);
            param.put("bce03", map.get("bce03").toString());
            param.put("vaf01List", vaf01List);
            param.put("vbg1List", vbg1List);
            
            if (cbm01List1.size()>0)
            {
                //删除医嘱单
                dao.removeCbm1(param);
            }
            if (vaf51List1.size()>0)
            {
                //删除诊疗申请单
                dao.removeVbq1(param);
            }
            //删除诊断记录
            dao.removeVao1(param);
            //删除医嘱记录
            dao.removeVaf1(param);
            //插入医嘱删除操作记录
            dao.addvbg1(param);
            
            mo.setResult(StaticKeys.OH_SUCCESS);
            return mo;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
    }

    @SuppressWarnings({"rawtypes", "unchecked", "unused"})
    public ModelVo backAdvice(Map map)
    {
        long t1 = System.currentTimeMillis();
        ModelVo mo = new ModelVo(StaticKeys.OH_SUCCESS);
        try
        {
            mo = horateTransferData(map);
            if(mo.getResult().equals("Failure")){
                return mo;
            }
            String cbm01s = GlobalVariable.StringIsNull(map.get("cbm01"));
            String[] cbm01arr = cbm01s.replace("{", "").replaceAll("}","").split(",");
            Set<String> cbm01Set = new HashSet<String>();
            for(String cbm01 : cbm01arr)
            {
                cbm01Set.add(cbm01);
            }
            String cbm01 = "";
            for(String temp : cbm01Set)
            {
                cbm01+= ","+temp;
            }
            cbm01 = cbm01.substring(1);
            cbm01 = "{"+cbm01+"}";
            map.put("cbm01", cbm01);
            //公共参数设置
            Map temp99 = new HashMap<>();
            temp99.put("productid", 9999);
            temp99.put("programid",9999);
            temp99.put("paramno",12);
            String apara269 = paraDao.getSysParamValue(temp99);
            Map temp98 = new HashMap<>();
            temp98.put("productid", 100);
            temp98.put("programid",105002);
            temp98.put("paramno",269);
            String fendanParam = paraDao.getSysParamValue(temp98);
            int lmember = Integer.parseInt(map.get("lmember").toString());
            if("0".equals(fendanParam))
            {
                apara269 = "0";
            }
            long t12 = System.currentTimeMillis();
            log.info(" ==============回退医嘱  fendanParam耗时====="+(t12-t1)+"毫秒=====================");
            List vaf1BackList = dao.queryVaf1BackList(map);
            long t10 = System.currentTimeMillis();
            log.info(" ==============回退医嘱  vaf1BackList耗时====="+(t10-t12)+"毫秒=====================");
            List vaj1BackList = dao.queryVaj1BackList(map);
            map.put("vaj1BackList", vaj1BackList);
            long t11 = System.currentTimeMillis();
            log.info(" ==============回退医嘱  vaj1BackList耗时====="+(t11-t10)+"毫秒=====================");
            List vbi1BackList = dao.queryVbi1BackList(map);
            long t9 = System.currentTimeMillis();
            log.info(" ==============回退医嘱  vbi1BackList耗时====="+(t9-t11)+"毫秒=====================");
            if(vbi1BackList==null && vbi1BackList.size()==0)
            {
                mo.setResultMsg("此医嘱单已结帐转移，不能再编辑");
                mo.setResult(StaticKeys.OH_FALSE);
                return mo;
            }
            List iaq1BackList = dao.queryIaq1BackList(map);
            if(!"0".equals(apara269) && iaq1BackList.size()>0)
            {
                mo.setResultMsg("此医嘱单对应医保费用已上传，不能再编辑");
                mo.setResult(StaticKeys.OH_FALSE);
                return mo;
            }
            long t91 = System.currentTimeMillis();
            log.info(" ==============回退医嘱  iaq1BackList耗时====="+(t91-t9)+"毫秒=====================");
            List temp97BackList = dao.temp97BackList(map);
            if(!"1".equals(apara269) && (temp97BackList!=null && temp97BackList.size()>0))
            {
                mo.setResultMsg("此医嘱单已经结帐或已扣费，不能在编辑");
                mo.setResult(StaticKeys.OH_FALSE);
                return mo;
            }
            long t92 = System.currentTimeMillis();
            log.info(" ==============回退医嘱  temp97BackList耗时====="+(t92-t91)+"毫秒=====================");
            List temp96BackList = dao.temp96BackList(map);
            if("1".equals(apara269) && (temp96BackList == null || temp96BackList.size()==0))
            {
                mo.setResultMsg("医嘱单对应所有单据已经结帐或已扣费，不能在编辑");
                mo.setResult(StaticKeys.OH_FALSE);
                return mo;
            }
            long t93 = System.currentTimeMillis();
            log.info(" ==============回退医嘱  temp96BackList耗时====="+(t93-t92)+"毫秒=====================");
            map.put("vaf1BackList", vaf1BackList);
            List vat1BackList1 = dao.queryVat1BackList1(map);
            List vat1BackList2 = dao.queryVat1BackList2(map);
            if((vat1BackList2!=null && vat1BackList2.size()>0) && (vat1BackList1==null || vat1BackList1.size()==0))
            {
                mo.setResultMsg("对应手术医嘱，手术室已安排，不能在编辑此医嘱");
                mo.setResult(StaticKeys.OH_FALSE);
                return mo;
            }
            long t94 = System.currentTimeMillis();
            log.info(" ==============回退医嘱  vat1BackList1耗时====="+(t94-t93)+"毫秒=====================");
            map.put("apara269",apara269);
            List htVafList = dao.queryHtVafList(map);
            if(htVafList==null || htVafList.size()==0)
            {
                mo.setResultMsg("没有需要编辑的医嘱明细");
                mo.setResult(StaticKeys.OH_FALSE);
                return mo;
            }
            long t2 = System.currentTimeMillis();
            log.info(" ==============回退医嘱  htVafList耗时====="+(t2-t94)+"毫秒=====================");
            log.info(" ==============回退医嘱  校验耗时====="+(t2-t1)+"毫秒=====================");
            map.put("htVafList", htVafList);
            //需要处理库存的数据
            List tmpDptList = dao.tmpDptList(map);
            List dptCl = dao.selectDEPTCl(map);
            List kbmVaiList = dao.kbmVaiList(map);
            Map map1 = new HashMap<>();
            map1.put("kbmVaiList", kbmVaiList);
            map1.put("apara269",apara269);
            map1.put("htVafList", htVafList);
            dao.updateVai1(map1);
            dao.updateVaj1(map1);
            dao.updateVaf1(map1);
            long t3 = System.currentTimeMillis();
            log.info(" =================回退医嘱 作废单据、费用、医嘱好耗时======="+(t3-t2)+"毫秒================");
            List temp95List = new ArrayList<>();
            for(Map temp : (List<Map<String,Object>>)htVafList)
            {
                if(Integer.parseInt(temp.get("vaf10").toString())==1)
                {
                    temp95List.add(temp);
                }
            }
            map1.put("temp95List", temp95List);
            dao.deletevbi1(map1);
            dao.deleteVbd1(map1);
            List vbgBackList = new ArrayList<>();
            for(Map temp : (List<Map>)htVafList)
            {
                Map<String,Object> temp9 = new HashMap<String,Object>();
                temp9.put("vbg01", getNewId.nextId());
                temp9.put("vaf01", temp.get("vaf01"));
                temp9.put("vbg03", 1);
                temp9.put("bce03", map.get("bce03"));
                if(Integer.parseInt(temp.get("vaf10").toString())==4)
                {
                    temp9.put("vbg06", "医嘱回退作废");
                }
                else
                {
                    temp9.put("vbg06", "临嘱发送医嘱回退");
                }
                vbgBackList.add(temp9);
            }
            map1.put("vbgBackList", vbgBackList);
            dao.addVbg1(map1);
            dao.deleteVat1(map1);
            long t4 = System.currentTimeMillis();
            log.info("=================回退医嘱 操作日志、删除病人手术信息耗时======="+(t4-t3)+"毫秒================");
            
            Map para46 = new HashMap<>();
            para46.put("productid", 9999);
            para46.put("programid",9999);
            para46.put("paramno",46);
            String para46V = paraDao.getSysParamValue(para46);
            if ("0".equals(para46V))
            {
                for (int i = 0; i < tmpDptList.size(); i++)
                {
                    yaopinKucunBo.gxDpsAndDpt(tmpDptList.get(i));
                }
            }
            // 材料库存预处理
            
            if (dptCl != null && dptCl.size() > 0)
            {
                //预处理库存--根据参数来判断9999-9999-46
                if("0".equals(para46V))
                {
                    for (int i = 0; i < dptCl.size(); i++)
                    {
                        yaopinKucunBo.gxDpsAndDptCl(dptCl.get(i));
                    }
                }
            }
            long t5 = System.currentTimeMillis();
            log.info("=================回退医嘱 回退库存耗时======="+(t5-t4)+"毫秒================");
            mo.setResult(StaticKeys.OH_SUCCESS);
            mo.setResultMsg("回退成功");
            long t6 = System.currentTimeMillis();
            log.info("=================回退医嘱 总耗时======="+(t6-t1)+"毫秒================");
        }
        catch(Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            mo.setResultMsg("数据异常，请联系管理员！");
        }
        return mo;
    }

    /**
     * 医嘱退费
     * @param map
     * @return
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public ModelVo vby1(Map map)
    {
        ModelVo mo = new ModelVo();
        try
        {
            
            /**
             * 根据界面参数vaf01s查询出的（cbm01,vaf01,vaf21tf）集合
             */
            List<Map<String, Object>> vaf01List = (List<Map<String, Object>>)JsonUtil.getList(GlobalVariable.StringIsNull(map.get("vaf01s")));
            if(vaf01List==null || vaf01List.size()==0)
            {
                mo.setResult(StaticKeys.OH_FALSE);
                mo.setResultMsg("请选择需要作废的医嘱！");
                return mo;
            }
            map.put("vaf01List",vaf01List);
            List hasVBy1List = dao.queryForList("removeAdvice.hasVby1", map);
            if(hasVBy1List!=null && hasVBy1List.size()>0)
            {
                mo.setResult(StaticKeys.OH_FALSE);
                mo.setResultMsg("医嘱已存在退费申请！");
                return mo;
            }
            /**
             * 查询kbmVAFList医嘱对应的费用信息,根据费用信息作出校验
             */
            List kbmVAJList = dao.kbmVAJList(map);
            if(kbmVAJList==null || kbmVAJList.isEmpty())
            {
                mo.setResult(StaticKeys.OH_FALSE);
                mo.setResultMsg("医嘱已经作废，或者没有需要作废的医嘱！");
                return mo;
            }
            for(Map tempVak : (List<Map>)kbmVAJList)
            {
            	if("0".equals(tempVak.get("vak01").toString()))
            	{
            		mo.setResult(StaticKeys.OH_FALSE);
                    mo.setResultMsg("未结账的医嘱不允许作废！");
                    return mo;
            	}
            }
            //判断是否有医嘱已经作废
            List temp94List = dao.temp94List(map);
            if(temp94List!=null && temp94List.size()>0)
            {
                mo.setResult(StaticKeys.OH_FALSE);
                mo.setResultMsg(((Map<String, Object>)temp94List.get(0)).get("vaf22")+" 已经作废，请刷新后在操作！");
                return mo;
            }
            //判断医嘱对应的作废数量是否大于原处方数量
            List temp93List = dao.temp93List(map);
            if(temp93List!=null && temp93List.size()>0)
            {
                mo.setResult(StaticKeys.OH_FALSE);
                mo.setResultMsg("作废数量大于原处方数量，请返回修正！");
                return mo;
            }
            //手术医嘱判断
            List temp92List = dao.temp92List(map);
            List temp91List = dao.temp91List(map);
            if((temp92List!=null && temp92List.size()>0) && (temp91List!=null && temp91List.size()>0))
            {
                mo.setResult(StaticKeys.OH_FALSE);
                mo.setResultMsg("对应手术医嘱，手术室已安排，不能在取消此医嘱！");
                return mo;
            }
            //医保已上传情况判断
            List temp90List = dao.temp90List(map);
            if(temp90List!=null && temp90List.size()>0)
            {
                mo.setResult(StaticKeys.OH_FALSE);
                mo.setResultMsg("对应医保费用已上传，不能在回退，请刷新后在操作！");
                return mo;
            }
            
            Map param24 = new HashMap<>();
            param24.put("productid", 100);
            param24.put("programid",105002);
            param24.put("paramno",160);
            String sysParam = paraDao.getSysParamValue(param24);
            List temp89List = dao.temp89List(map);
            if("1".equals(sysParam)&&(temp89List!=null && temp89List.size()>0))
            {
                mo.setResult(StaticKeys.OH_FALSE);
                mo.setResultMsg(((Map<String, Object>)temp89List.get(0)).get("vaf22")+"对应退费还没审核，不能继续退费");
                return mo;
            }
            //
            List temp88List = dao.queryForList("removeAdvice.temp88List", map);
            if(temp88List==null || temp88List.size()==0)
            {
                mo.setResult(StaticKeys.OH_FALSE);
                mo.setResultMsg("取作废医嘱记录错误!");
                return mo;
            }
            ///////-----------------------Go
         /*   //修改病人医嘱记录vaf1 表
            dao.updatevaf1_1(map);
            //新增医嘱操作记录---sql未写
            dao.addVbg1_1(map);
            
            //病人退费需要医师先取消医嘱(系统参数)
            if("1".equals(sysParam))
            {
                //更新计价信息表
                //dao.updateVbd1_1(map);
                //新增退费申请记录
                dao.addVBY1_1(map);
                //更新费用信息
                dao.updateVaj1_1(map);
            }*/
            map.put("param24", sysParam);
            dao.update("removeAdvice.updateVaf_Vaj_Vby", map);
            mo.setResult(StaticKeys.OH_SUCCESS);
            mo.setResultMsg("作废成功");
            return mo;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            mo.setResultMsg(e.toString());
            return mo;
        }
    }
    /**
     * 历史表转当前表
     * @param map
     * @return
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public ModelVo horateTransferData(Map map)
    {
        ModelVo mo = new ModelVo(StaticKeys.OH_SUCCESS);
        String date1 = MapUtils.getString(map,"date1");
        String date2 = MapUtils.getString(map,"date2");
        int range = DateUtil.timeRange(date1,date2);
        if(range>0){
            String type = "";
            String[] vak01s = StringUtils.split(MapUtils.getString(map,"vak01s"),",");
            try {
                if(vak01s.length>0){
                    for(int i=0;i<vak01s.length;i++){
                        type = dao.horateTransferData(vak01s[i]);
                        if(!type.equals("")){
                            mo.setResult(StaticKeys.OH_FALSE);
                            mo.setResultMsg(type);
                            return mo;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mo;
    }
}
